package org.smarthings.things.management.impl;

import java.util.Map;

import org.smarthings.things.management.Thing;
import org.smarthings.things.management.ThingAction;
import org.smarthings.things.management.metadata.ThingActionMetadata;

public class ThingActionImpl implements ThingAction {

	private String UUID;
	private String name;

	private Thing thing;
	private ThingsEventPropagator thingsEventPropagator;
	private ThingActionMetadata metadata;
	private Map<String, Object> lastExecutionArguments;

	public ThingActionImpl(String name, ThingActionMetadata metadata,
			ThingsEventPropagator thingsEventPropagator) {
		this.name = name;
		this.thingsEventPropagator = thingsEventPropagator;
		this.metadata = metadata;
		this.UUID = generateThingActionUUID();
	}

	@Override
	public String getUUID() {
		return UUID;
	}

	@Override
	public String getName() {
		return name;
	}
	
	@Override
	public String getType() {
		return name;
	}

	@Override
	public void execute(Map<String, Object> arguments) throws Exception {
		lastExecutionArguments = arguments;
		thingsEventPropagator.fireThingActionExecutionEvent(thing, this, arguments);
	}

	@Override
	public Map<String, Object> getLastExecutionArguments() {
		return lastExecutionArguments;
	}

	@Override
	public ThingActionMetadata getMetadata() {
		return metadata;
	}

	void bindThing(Thing thing) {
		this.thing = thing;
	}

	private static long index = 0;

	private static String generateThingActionUUID() {
		return String.valueOf(++index);
	}

}
